// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV 
})
const axios = require('axios');
const cheerio = require('cheerio');
const db = cloud.database();
async function getReq(url,data){
  return new Promise(function(resolve,reject){
    axios({
      method:'GET',
      url:url,
      data:data,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1 Edg/92.0.4515.131'
      }
    }).then(response=>{
      resolve(response.data)
    })
  })
}
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let page = event.page || 1
  let query = event.query || 'Java'
  let requrl = 'http://interlib.sdust.edu.cn/opac/m/search?curlibcode=01000&page='+page+'&q='+query
  requrl = encodeURI(requrl)
  let reqData = await getReq(requrl,{})
  /**调用新增查询记录 */
  cloud.callFunction({
    name:'cloud-log-api',
    data:{
      action:'incOne',
      openid:wxContext.OPENID,
      word:query
    }
  })
  /** 加载爬虫 */
  let bookList = [];
  $ = cheerio.load(reqData);
  let bookObj = {};
  /**爬虫爬取基础图书信息 */
  $('td em').each(function(index,ele){
    let baseStr = $(this).text().trim()
    if(index%5 == 0){
      bookObj.bookName = baseStr
    }else if(index%5 == 1){
      bookObj.bookAuthor = baseStr
    }else if(index%5 == 2){
      bookObj.bookPublish = baseStr
    }else if(index%5 == 3){
      bookObj.bookDate = baseStr
    }else if(index%5 == 4){
      baseStr = baseStr.replace(/\n/g,'')
      baseStr = baseStr.replace(/\s+/g,"");
      bookObj.bookType = baseStr
      bookList.push(bookObj)
      bookObj = {}
    }
  })
  /**爬虫爬取图书ISBN 信息 */
  let isbnList = []
  $('.bookcover_img').each(function(index,ele){
    let isbnStr = $(this).attr('isbn')
    let bookNo = $(this).attr('bookrecno')
    isbnStr = isbnStr.replace(/-/g,'')
    console.log(isbnStr)
    let obj = bookList[index]
    obj.isbn = isbnStr
    obj.bookNo = bookNo
    isbnList.push(isbnStr)
    bookList[index] = obj
  })
  let isbns = isbnList.toLocaleString()
  let isbnReqData = await getReq('https://book-resource.dataesb.com/websearch/metares?glc=U1SD0532017&cmdACT=getImages&type=0&isbns='+isbns,{})
  isbnReqData = isbnReqData.replace("showCovers(",'')
  isbnReqData = isbnReqData.replace("(",'')
  isbnReqData = isbnReqData.replace(")",'')
  let coverList = JSON.parse(isbnReqData).result;
  /**二重遍历匹配封面图 */
  let bookLen = bookList.length;
  let coverLen = coverList.length;
  for(var i=0;i<bookLen;i++){
    let bookData = bookList[i];
    for(var j=0;j<coverLen;j++){
      let coverData = coverList[j];
      if(bookData.isbn == coverData.isbn){
        bookData.bookCover = coverData.coverlink
        bookList[i] = bookData
        break
      }
    }
    if(bookData.bookCover == undefined){
      bookData.bookCover = 'https://6465-dev-tool-0gx69s0m12d6add1-1304670744.tcb.qcloud.la/PicBed/book.png?sign=9ec21d1581955f7f8bd9cda8cd6647b0&t=1629555181'
      bookList[i] = bookData
    }
  }
  console.log(coverList)
  console.log(bookList)
  return bookList;
}